#include "danmuflie.h"
#include <QDir>
#include<QDebug>
#include<QFile>
#include<QList>
#include<QMap>
#include<QTextCodec>
DanmuFlie::DanmuFlie(QObject *parent) : QObject(parent)
{

}
bool DanmuFlie::isFileExist(QString fileName){
    filePath = "C:/Users/EDY/Videos/"+fileName+".txt";

    qDebug()<<filePath;
    bool flag=QFile::exists(filePath);
    if(flag){
     qDebug()<<"该视频已创建弹幕文件";
    }else {
        qDebug()<<"未找到弹幕文件";
    }

    this->createDanmuFile(filePath,flag);

}
void DanmuFlie::createDanmuFile(const QString &filePath,bool flag){

    if(flag==false){
        //创建一个弹幕文件
        qDebug()<<"正在创建弹幕文件";
        QFile file(filePath);
        file.open(QIODevice::WriteOnly);
        file.close();

    }

    danmuFile=new QFile(filePath);

    if(!danmuFile->open(QIODevice::ReadWrite|QIODevice::Append)){
        qDebug()<<"打开文件失败";
    }
    stream=new QTextStream(danmuFile);

     stream->setCodec(QTextCodec::codecForName("UTF-8"));

}
void DanmuFlie::writeIntoFile(QString content,int time){
    //将弹幕的数据格式化
    *stream<<time<<",";
    *stream<<content<<endl;

}
//当弹幕文件的数量过大时，就会占用主线程的操作。
void DanmuFlie::translateFile(){



    QFile file(filePath);
    file.open(QIODevice::ReadOnly);


    while (!file.atEnd()) {
       QString str=file.readLine();
//       qDebug()<<str;
       //去掉每一行末尾的换行
      str.remove("\n");

      QStringList strlist=str.split(',');



      //将每一行弹幕内容和对应的时间戳保存在map当中
      map.insert(strlist[0].toInt(),strlist[1]);


    }
    //遍历map容器
    QMap<int,QString>::const_iterator iter;
    for(iter=map.begin();iter!=map.end();iter++){
        qDebug()<<"弹幕时间为"<<iter.key()<<"弹幕内容为"<<iter.value();
    }
    file.close();

    emit finish();
}

DanmuFlie::~DanmuFlie()
{
    danmuFile->close();//关闭文件，但不释放内存资源
    delete danmuFile;//释放堆内存资源

    delete stream;
}
